package com.example.springboot3.controller;

import com.example.springboot3.model.Articleinfo;
import com.example.springboot3.model.User1;
import com.example.springboot3.service.User1Service;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
@Controller
@ResponseBody
@RequestMapping("/user")
public class User1Controller {
    @Resource
    private User1Service user1Service;
    //查询全部
    @RequestMapping("/getAll")
    public List<User1> getAll(){
        return user1Service.getAll();
    }
    @GetMapping("getAllPlus")
    //直接工具人user1Service了,没有创建新的Service
    public List<Articleinfo> getAllPlus(){
        return user1Service.getAllPlus();
    }
    //添加一行内容
    @RequestMapping("/insert")
    public int insert(User1 user1){
        if (user1 == null || user1.getUsername() == null || user1.getPassword() == null ||
                "".equals(user1.getPassword()) || "".equals(user1.getUsername())){
            return 0;
        }
        return user1Service.insert(user1);
    }
    @RequestMapping("/insert2")
    public int insert2(User1 user1){
        if (user1 == null || user1.getUsername() == null || user1.getPassword() == null ||
                "".equals(user1.getPassword()) || "".equals(user1.getUsername())){
            return 0;
        }
        user1Service.insert2(user1);
        return user1.getId();
    }
    @GetMapping("/update")
    public int update(Integer id,String password){
        return user1Service.update(id,password);
    }
    @GetMapping("/delete")
    public int delete(Integer id){
        return user1Service.delete(id);
    }
    @GetMapping("/selectLike")
    public List<User1> selectLike(String str){
        return user1Service.selectLike(str);
    }
    @GetMapping("error")
    public void error(){
        Object object = null;
        object.hashCode();
        return;
    }
    @Transactional
    @GetMapping("/transactional")
    public int transactional(){
        User1 user1 = new User1();
        user1.setUsername("trans");
        user1.setPassword("trans");
        int tmp = user1Service.insert(user1);
        try {
            //被try catch 包裹后,发生异常不会回滚
            int num = 10/0;
        } catch (Exception e) {
            System.out.println("发生了异常: " + e.toString());
            tmp = 0;
            //想要发生回滚的方法一:抛出异常
            //throw e;
            //方法二:手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return tmp;
    }
}
